<template>
  <div>
    <FormPanel ref="form" :list="form" :cols="4" :labelWidth="90" :isSubmitBtn="false" @formChange="changeHandle" />
    <ButtonArea :containerStyle="{ paddingLeft: '90px' }">
      <el-button size="small" type="primary" :disabled="buildBtn" @click="newBuild">新建</el-button>
      <AjaxButton size="small" type="primary" :disabled="saveltBtn" :click="saveSales">保存</AjaxButton>
      <AjaxButton size="small" type="primary" :disabled="outStockBtn" :click="outStock">出库</AjaxButton>
      <el-button size="small" type="primary" :disabled="cancelBtn" @click="cancel">取消</el-button>
      <AjaxButton size="small" type="primary" :disabled="printlSalesBtn" :click="printlSales">打印销售单</AjaxButton>
      <!-- <AjaxButton size="small" type="primary" :disabled="printlSettlementBtn" :click="printlSettlement">打印销售结算单</AjaxButton> -->
      <AjaxButton size="small" type="primary" :disabled="printFlag" :click="printHandle">打印出库单</AjaxButton>
      <AjaxButton size="small" type="primary" :disabled="deleteBtnState" :click="deleteSales">作废</AjaxButton>
    </ButtonArea>

    <FilterTable
      ref="table"
      columnsRef="partPartOutboundPartSalesIndex"
      height="400px"
      minHeight="400px"
      :columns="columns"
      :dataSource="listTable"
      :isMemoryPagination="true"
      :onCellChange="changeData"
      :onRowSelectChange="selectTableFun"
      :onSyncTableData="syncTableFun"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <!-- <template slot="moreActions">
        <span @click="() => deleteHandle()">删除数据</span>
      </template> -->
      <template slot="controls" slot-scope>
        <el-button size="small" type="primary" icon="el-icon-plus" :disabled="addbtn" @click="addFun">新增</el-button>
        <UploadFile
          style="margin: 0 10px;"
          :initial-value="fileInitalValue"
          isOnlyButton
          :limit="20"
          type="primary"
          icon="el-icon-download"
          :disabled="impbtn"
          :actionUrl="`${server.DMSCLOUD_PART}/basedata/ttSalesPart/importSalesPart`"
          @change="handleUploadChange"
          >导入</UploadFile
        >
        <el-button size="small" type="primary" :disabled="impbtn" :loading="exportModelLoading" @click="exportModel">导出模板</el-button>
        <AjaxButton size="small" type="primary" :disabled="printFlag" :click="exportClick">导出</AjaxButton>
        <!-- <el-button size="small" type="primary" icon="el-icon-upload2" :loading="exportLoading" :disabled="exportbtn" @click="exportFun">导出</el-button> -->
      </template>
    </FilterTable>
    <div style="margin-top:40px">
      <FormPanel ref="form2" :cols="4" :list="formList" :labelWidth="90" :isSubmitBtn="false" @formChange="changeHandle2"></FormPanel>
    </div>
    <BaseDialog
      :visible.sync="visibleSales"
      title="配件销售单查询"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
      @viewportChange="viewportChange"
    >
      <salesOrder :ptype="ptype" :maxHeight="maxHeight" :salesNo="salesNo" @saveDialog="getSelectSales" @closeSalesDialog="visibleSales = false" />
    </BaseDialog>
    <BaseDialog :visible.sync="networkOrder.visible" :title="networkOrder.title" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <network-order @saveDialog="getSelectSales" @close="networkOrder.visible = false" />
    </BaseDialog>
    <BaseDialog :visible.sync="orderVisible" title="选择工单" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <order :workNo="search_order" @saveDialog="getSelectNo" @closeDialog="orderVisible = false"></order>
    </BaseDialog>

    <BaseDialog :visible.sync="customerVisible" title="客户选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <customer @saveDialog="getCustomer" @close="customerVisible = false" />
    </BaseDialog>
    <BaseDialog :visible.sync="vehicleOwnerVisible" title="选择车主" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <vehicleOwner @close="vehicleOwnerVisible = false" @saveDialog="getvehicleOwner" />
    </BaseDialog>

    <Drawer :visible.sync="salesOrderAddVisible" width="70%" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <salesOrderAdd :customerCode="customerCode" :priceAddRate="priceAddRate" :salesBasePriceType="salesBasePriceType" @changedata="passValue" @close="salesOrderAddVisible = false" />
    </Drawer>

    <BaseDialog :visible.sync="salesOrderChangeVisible" title="配件编辑" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <salesOrderChange :rate="1" :rowData="formData" @saveDialog="changeEdit" @close="salesOrderChangeVisible = false" />
    </BaseDialog>

    <BaseDialog :visible.sync="checkStockVisible" title="负库存提示信息" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <checkStock
        :checkData="checkData"
        @saveDialog="check1"
        @close="
          checkStockVisible = false;
          checkData = [];
        "
      />
    </BaseDialog>
    <!-- 打印出库单 -->
    <div v-if="showPrint">
      <BasePrint ref="print" :data="printList" template="templateOut" />
    </div>
    <!-- 打印销售单 -->
    <div v-if="handleDyone">
      <BasePrint ref="Salesprint" :data="SalesprintList" template="templateSales" />
    </div>
    <!-- 结算单打印 -->
    <div v-if="handleDdtwo">
      <BasePrint ref="Settlementsprint" :data="SettlementprintList" template="templateSettlement" />
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import salesOrder from './salesOrder';
import networkOrder from './networkOrder';
import SERVER from '@/api/server';
import order from './order';
import { isAuthorized, arrayObjDeWeight, setRound } from '@/utils/index'; // 权限
import customer from './searchCustomerPage';
import vehicleOwner from './vehicleOwner';
import salesOrderAdd from './salesOrderAdd';
import salesOrderChange from './salesOrderChange';
import checkStock from './checkStock';
import { queryCompanyInforById } from '@/api/part/common';
import { getCompanyId } from '@/assets/js/auth';
import { getOrgByOrgType } from '@/api/part/partOutbound/internalReceive/index';
import { queryVipInfoByRono, queryVipInfoByBillNo } from '@/api/finance/repairFinance/cancelFinance';
import { doSearch } from '@/api/tool/basic/toolParams';
import { dealerPrintApi } from '@/api/repair/index.js';

// import { printData } from '@/api/part/partOut/partSales/index';

import {
  serviceConsultant,
  partSalesItem,
  unLocked,
  roNo,
  partSalesIfBear,
  save,
  enterRecord,
  deleted,
  getStorageNum,
  deleteAll,
  partSalesExport,
  printData,
  printDataTwo,
  exportSalesModel,
  delSalesPartInfo,
  exportData
} from '@/api/part/partOut/partSales/index';
import { log } from 'util';
import { constants } from 'buffer';
import { getAllUser } from '@/api/customerRepair/afterSaleVisit/resultEntry';
import { findAllRepair } from '@/api/repair/basicParameters';
// 查询服务顾问
import { searchRoleByCode } from '@/api/common/empSelect/index';
import dictCode from '@/utils/dictCode';
import { getStroageList } from '@/api/part/partOutbound/partBreak';
import { exportExcelFile, notifyAction } from '@/utils/index';
import { getOwnerCode } from '@/assets/js/auth';
// 获取员工
import { getDealerUser } from '@/api/customerRepair/customerComplaint/customerComplaintReception';
import { getSysParaValueByCode } from '@/api/part/access/accessInventory';
import NetworkOrder from './networkOrder.vue';
export default {
  name: 'partSales',
  components: {
    salesOrder,
    order,
    customer,
    vehicleOwner,
    salesOrderAdd,
    salesOrderChange,
    checkStock,
    networkOrder
  },
  mixins: [dictionary],
  data() {
    this.conf = { add: '新增', edit: '编辑' };
    this.baseTable = null;
    return {
      cunUserList: [], // 存所有人的数组
      printDataList: [],
      server: SERVER,
      printDataListTwo: [],
      handleDyone: false,
      handleDdtwo: false,
      form: this.createForm(),
      // fetchApi: partSalesItem,
      // fetchParams: { xhrAbort: true }, //调用数据
      isEdit: false,
      visibleSales: false,
      orderVisible: false,
      exportLoading: false,
      exportModelLoading: false,
      customerVisible: false,
      vehicleOwnerVisible: false,
      salesOrderAddVisible: false,
      salesOrderChangeVisible: false,
      checkStockVisible: false,
      isShow: false,
      dialogTitle: '',
      listType: [],
      search_order: '',
      priceAddRate: 1,
      salesBasePriceType: '',
      salesNo: '',
      columns: this.createTableColumns(),
      formList: this.createFormList(),
      list: {},
      serviceAdvisorData: [],
      formData: '',
      itemId: '',
      flag: '',
      rate: 0.13,
      listTable: [],
      flagStuats1: true,
      typeStatus: 0, // 定义改销售单的状态
      VIN: '', // 定义VIN
      customerCode: null, // 客户代码
      customerCodeIn: null, // 供應商代碼
      finishStatus: 10041002,
      items: [], // 删除行
      flagStuats: true, // 判断状态
      syncTableList: [],
      checkData: [],
      fetchParam: {},
      fetchParam2: {},
      deleteList: [], // 用于清空操作时候集合
      buildBtn: false,
      saveltBtn: true,
      outStockBtn: true,
      cancelBtn: true,
      printlSalesBtn: true, // 打印销售单按钮  原 true
      printlSettlementBtn: true, // 打印销售结算单按钮 原 true
      deleteBtnState: true,
      addbtn: true,
      exportmolbtn: true,
      impbtn: true,
      exportbtn: true,
      enDisabled: false,
      codeName: [],
      SalesprintList: {}, // 打印销售单
      SettlementprintList: {}, // 打印销售结算单
      selectRow: null,
      delFlag: null,
      fileInitalValue: [],
      showPrint: false, // 打印显示
      printList: {}, // 打印数据
      printFlag: true, // 打印按钮是否禁用
      departmentList: [], // 部门
      maxHeight: 200,
      outboundPrintParams: {}, // 出库单打印
      settlementPrintParams: {}, // 配件销售结算单打印
      paraArr: [],
      XSJSDSM: '',
      saleOrderPrintParams: {}, // 配件销售单打印
      networkOrder: { title: '', type: 'default', visible: false, data: {} }
    };
  },
  computed: {
    ptype() {
      // console.log(this.$route.meta.ptype, '模块');

      return this.$route.meta.ptype;
    } // 模块区分
  },
  mounted() {
    this.baseTable = this.$refs.table.$refs.pageTable;
    this.getDealerUser();
    this.serviceConsultant();
    this.getQueryBookingInformation();
    this.searchstore();

    // this.getOrgByOrgType(); // 部门
    // 查询各个打印单据参数配置
    // this.queryOutboundPrintParams();
    // this.querySettlementPrintParams();
    // this.querySaleOrderPrintParams();
  },
  methods: {
    viewportChange(val) {
      if (val === 'default') {
        this.maxHeight = 200;
      } else {
        this.maxHeight = window.innerHeight - 300;
      }
    },
    async getToolParams() {
      try {
        const res = await doSearch({ module: this.$route.meta.ptype ? 'bou' : 'spa' });
        if (res.resultCode === 200) {
          console.log('res.data', res.data);
          // 获取销售单说明
          let para = ['XSDSM', 'XSDSM1', 'XSDSM2'];
          let paraArr = [];
          para.forEach(x => {
            console.log(x);
            res.data.find(item => item.para == x).bParaValue && this.paraArr.push(res.data.find(item => item.para == x).bParaValue);
          });
          // 获取销售结算单
          para.forEach(x => {
            res.data.find(item => item.para == 'SSJSDSM').bParaValue && (this.XSJSDSM = res.data.find(item => item.para == 'SSJSDSM').bParaValue);
          });
          console.log('this.XSJSDSM', this.XSJSDSM);
          console.log('这是获取销售单说明的地方', this.paraArr);
        }
      } catch (e) {}
    },
    // 获取部门
    // 获取部门字典
    async getOrgByOrgType() {},
    // 打印出库单数据接口
    async getPrintData() {
      // console.log(this.selectColumns[0].PART_ALLOCATE_IN_ID);
      const res = await printData(this.selectRow[0].SALES_PART_NO); // 获取当前行数据
      this.printList = res.data;
    },
    // 打印出库单
    async printHandle() {
      // 判断是否选中数据
      if (this.selectRow.length < 1) {
        return this.$notify.error({ title: '提示信息', message: '请选中一条数据' });
      }
      await this.getPrintData();
      this.showPrint = true;
      this.printList.baseInfo.USER_NAME = this.cunUserList.find(item => item.userId == this.printList.baseInfo.USER_ID).employeeName || '';
      this.printList.baseInfo.CREATED_NAME = this.cunUserList.find(item => item.userId == this.printList.baseInfo.CREATED_BY).employeeName || '';
      if (this.printList.baseInfo.SALES_PART_AMOUNT) {
        this.printList.baseInfo.SALES_PART_AMOUNT = setRound(this.printList.baseInfo.SALES_PART_AMOUNT);
      }
      // console.log(this.printList);
      // 打印
      this.$nextTick(() => {
        // console.log(123);
        this.$refs.print.EXCUTE_PRINT();
      });
    },
    createForm() {
      return [
        {
          type: 'INPUT',
          label: '配件销售单号',
          fieldName: 'salesPartNo',
          disabled: false,
          initialValue: null,
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={this.partsOrder}></el-button>;
          },
          onEnter: val => {
            this.partsOrder();
          }
        },
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'roNo',
          hidden: true,
          disabled: true,
          readonly: true,
          initialValue: null,
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={this.order}></el-button>;
          },
          onEnter: val => {
            this.search_order = val;
            this.order();
          }
        },
        {
          type: 'SELECT',
          label: '选择类型',
          fieldName: 'type',
          initialValue: 'customer',
          disabled: true,
          itemList: [
            { text: '客户', value: 'customer' },
            { text: '车主', value: 'vehicleOwner' }
          ],
          change: val => {
            this.changeCustomer(val);
          }
        },
        {
          type: 'INPUT',
          label: '客户代码',
          hidden: true,
          fieldName: 'customerCode'
        },
        {
          type: 'INPUT',
          label: '客户',
          fieldName: 'customerName',
          initialValue: null,
          disabled: true,
          readonly: true,
          rules: [{ required: true, message: '请选择客户', trigger: 'blur' }],
          unitRender: props => {
            if (this.form.find(item => item.fieldName === 'customerName').label == '车主') {
              return <el-button icon="el-icon-search" onClick={() => this.vehicle(props)}></el-button>;
            } else {
              return <el-button icon="el-icon-search" onClick={() => this.customer('customerName')}></el-button>;
            }
          }
        },
        {
          type: 'SELECT',
          label: '销售顾问',
          fieldName: 'consultant',
          disabled: true,
          filterable: true,
          itemList: []
        },
        {
          type: 'INPUT',
          label: '网络订单号',
          hidden: true, //暂时隐藏
          fieldName: 'partPlatformOrderNo', // PART_PLATFORM_ORDER_NO
          placeholder: '请输入...',
          disabled: true,
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={this.networkOrderSearch}></el-button>;
          }
        },
        {
          type: 'INPUT',
          label: '备注',
          disabled: true,
          fieldName: 'remark'
        }
      ];
    },
    createTableColumns() {
      let that = this;
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          render: props => {
            return (
              <div>
                <el-button
                  size="mini"
                  disabled={props.row.IS_FINISHED === 10041001 || props.row.BALANCE_STATUS == 10041001 || props.row.PART_QUANTITY < 0 ? true : false}
                  type="text"
                  onClick={() => this.deleteHandle(props.row)}
                >
                  删除
                </el-button>
                <el-button
                  size="mini"
                  disabled={props.row.IS_FINISHED === 10041001 || props.row.BALANCE_STATUS == 10041001 || props.row.PART_QUANTITY < 0 ? true : false}
                  type="text"
                  onClick={() => this.editHandle(props.row)}
                >
                  编辑
                </el-button>
              </div>
            );
          }
        },
        {
          title: '是否出库',
          dataIndex: 'IS_FINISHED',
          dictItems: this.createDictList('1004'),
          hidden: true
        },
        {
          title: '仓库名称',
          dataIndex: 'STORAGE_CODE',
          sorter: true,
          dictItems: [],
          filter: true,
          filterType: 'checkbox',
          filterItems: []
        },
        {
          title: '库位',
          dataIndex: 'STORAGE_POSITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },

        {
          title: '单位',
          dataIndex: 'UNIT_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '单位代码',
        //   dataIndex: 'UNIT_CODE',
        //   render: props => {
        //     return <span v-if={this.isShow}>{props.row.UNIT_CODE}</span>;
        //   }
        // },
        {
          title: '数量',
          sorter: true,
          dataIndex: 'PART_QUANTITY',
          filter: true,
          filterType: 'number'
        },
        {
          title: '配件销售单价',
          dataIndex: 'PART_SALES_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '配件销售金额',
          dataIndex: 'PART_SALES_AMOUNT',
          render: props => {
            props.row.PART_SALES_AMOUNT = this.numFilter((+props.row.PART_SALES_PRICE ? +props.row.PART_SALES_PRICE : 0) * +props.row.PART_QUANTITY);
            return <span>{props.row.PART_SALES_AMOUNT}</span>;
          },
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '收费金额',
          dataIndex: 'SALES_AMOUNT',
          render: props => {
            props.row.SALES_AMOUNT = this.numFilters((+props.row.PART_SALES_PRICE ? +props.row.PART_SALES_PRICE : 0) * +props.row.PART_QUANTITY, +props.row.DISCOUNT);
            return <span>{props.row.SALES_AMOUNT}</span>;
          },
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '电池序列号',
          dataIndex: 'BATTERY_SEQUENCE',
          editable: true,
          defaultEditable: true,
          // editType: 'number',
          disabled: false,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '成本价',
          dataIndex: 'PART_COST_PRICE',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        }
        // {
        //   title: '网络订单号',
        //   dataIndex: 'PART_PLATFORM_ORDER_NO'
        // }
      ];
    },
    createFormList() {
      return [
        // {
        //   type: 'INPUT',
        //   label: '品种合计',
        //   fieldName: 'kindNum',
        //   disabled: true
        // },
        // {
        //   type: 'INPUT',
        //   label: '数量合计',
        //   fieldName: 'partNum',
        //   disabled: true
        // },
        {
          type: 'INPUT',
          label: '销售合计金额',
          fieldName: 'edtMoney',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '收费合计金额',
          fieldName: 'salesPartAmount',
          disabled: true
        }
      ];
    },
    // 筛选处增加使用价格类型（整单的）更改时，修改行项目的价格类型及售价等
    changeType(val) {
      this.syncTableList.forEach(x => {
        if (x.BALANCE_STATUS == 10041001) {
          return;
        }
        x.PRICE_TYPE = val;
        // 不含税成本价
        if (val == 80501001) {
          // 判断字段是否为空
          if (x.COST_PRICE != null) {
            var listPrice = x.COST_PRICE;
          } else {
            var listPrice = 0;
          }
          this.changeMoney(listPrice, x);
        } else if (val == 80501002) {
          // 含税销售价
          if (x.SALES_PRICE != null) {
            var listPrice = x.SALES_PRICE;
          } else {
            var listPrice = 0;
          }
          this.changeMoney(listPrice, x);
        } else if (val == 80501010) {
          // 含税采购价
          if (x.PLAN_PRICE != null) {
            var listPrice = x.PLAN_PRICE * (1 + Number(this.rate));
          } else {
            var listPrice = 0;
          }
          this.changeMoney(listPrice, x);
        } else if (val == 80501011) {
          // 含税批发价
          if (x.COST_WHOLESALES_PRICE != null) {
            var listPrice = x.COST_WHOLESALES_PRICE;
          } else {
            var listPrice = 0;
          }
          this.changeMoney(listPrice, x);
        }
      });
      this.salesBasePriceType = val;
    },
    changeMoney(val, item) {
      item.PART_SALES_PRICE = this.numFilter(val);
      if (val != 0) {
        item.PRICE_RATE = this.numFilter(val / val); // 金额改变时候改变参数
      }
      const num = item.PART_QUANTITY;
      item.SALES_AMOUNT = this.numFilter(val * num);
    },
    // 销售单打印数据
    async printData() {
      const res = await printData(this.form.find(item => item.fieldName === 'salesPartNo').initialValue);
      this.printDataList = res.data;
    },
    // 销售结算单打印数据
    async printDataTwo() {
      const res = await printDataTwo(this.form.find(item => item.fieldName === 'salesPartNo').initialValue);
      this.printDataListTwo = res.data;
    },
    // 获取所有人的信息
    async getDealerUser() {
      const res = await getDealerUser();
      let userData = arrayObjDeWeight(res.data, 'userId');
      // this.columns.find(x => x.dataIndex == 'CREATED_BY').dictItems = this.columns.find(x => x.dataIndex == 'CREATED_BY').filterItems = this.columns.find(
      //   x => x.dataIndex == 'CREATED_BY'
      // ).editItems = userData.map(x => ({
      //   text: x.employeeName,
      //   value: x.userId + ''
      // }));
      this.cunUserList = userData;
    },
    // 修改行项目时更新售价等
    changeData(keys, val) {
      const [key] = Object.keys(keys);
      const changeKey = key.split('|')[1];
      const changeValue = keys[key];
      if (changeKey == 'PRICE_TYPE') {
        if (changeValue == 80501001) {
          // 判断字段是否为空
          if (val.COST_PRICE != null) {
            var listPrice = val.COST_PRICE;
          } else {
            var listPrice = 0;
          }
          this.changeMoney(listPrice, val);
        } else if (changeValue == 80501002) {
          // 含税销售价
          if (val.SALES_PRICE != null) {
            var listPrice = val.SALES_PRICE;
          } else {
            var listPrice = 0;
          }
          this.changeMoney(listPrice, val);
        } else if (changeValue == 80501010) {
          // 含税采购价
          if (val.PLAN_PRICE != null) {
            var listPrice = val.PLAN_PRICE * (1 + Number(this.rate));
          } else {
            var listPrice = 0;
          }
          this.changeMoney(listPrice, val);
        } else if (changeValue == 80501011) {
          // 含税批发价
          if (val.COST_WHOLESALES_PRICE != null) {
            var listPrice = val.COST_WHOLESALES_PRICE;
          } else {
            var listPrice = 0;
          }
          this.changeMoney(listPrice, val);
        }
      }
      // 取消出库按钮
      this.outStockBtn = true;
      this.syncTableFun(this.syncTableList);
    },
    changeCustomer(value) {
      this.form.find(item => item.fieldName === 'customerName').initialValue = null;
      if (value == 'customer') {
        this.form.find(item => item.fieldName === 'customerName').label = '客户名称';
        this.form.find(item => item.fieldName === 'customerName').rules[0].message = '请选择客户';
      } else if (value == 'vehicleOwner') {
        this.form.find(item => item.fieldName === 'customerName').label = '车主';
        this.form.find(item => item.fieldName === 'customerName').rules[0].message = '请选择车主';
      }
    },
    async getQueryBookingInformation() {
      let res = await getAllUser();
      this.serviceAdvisorData = res.data.map(x => ({ text: x.employeeName, value: x.userId }));
      // let re = await findAllRepair();
      // sessionStorage.setItem('precision', re.data['8011']);
      // sessionStorage.setItem('settlementType', re.data['1009']);
    },
    getEmployeeName(userId) {
      const item = this.serviceAdvisorData.find(x => {
        return x.value == userId;
      });
      return item ? item.text : '';
    },
    async serviceConsultant() {
      let roleParam = { role: dictCode.SERVICE_CONSULTANT };
      const res = await searchRoleByCode(roleParam);
      if (res.resultCode == 200) {
        this.form.find(item => item.fieldName === 'consultant').itemList = res.data.map(x => ({ text: x.employeeName, value: x.userId }));
      }
    },

    // 保留两位小数
    numFilter(value) {
      let realVal = parseFloat(value).toFixed(2);
      return realVal;
    },
    numFilters(value1, value2) {
      let res = String(value2).split('.');
      let num = 0;
      if (res[1] != undefined) {
        num = res[1].length;
      }
      if (value2) {
        let a = value2 - 0.01;
        let b = 1 - value2;
        if ((a >= 0 && b >= 0 && num <= 2) || value2 == 0) {
          let value = value1 * value2;
          let realVal = parseFloat(value).toFixed(2);
          return realVal;
        }
      }
    },

    changeHandle(val) {
      this.fetchParam = Object.assign({}, val);
    },
    changeHandle2(val) {
      this.fetchParam2 = Object.assign({}, val);
    },
    selectTableFun(val) {
      this.selectRow = val;
      if (this.selectRow && this.selectRow.length > 0) {
        this.delFlag = this.selectRow[0].BALANCE_STATUS != 10041001;
      }
    },
    // 导出点击事件
    async exportClick() {
      // if (this.partColumns.length <= 0) {
      //   return this.$notify.error({ title: '提示信息', message: '请选择一条数据' });
      // }
      let searchParams = await this.$refs.form.GET_FORM_DATA();
      let res = await exportData(searchParams[1]);
      exportExcelFile(res.data, '配件销售');
    },
    // 新建
    newBuild() {
      this.form.find(item => item.fieldName === 'salesPartNo').disabled = true;
      this.form.find(item => item.fieldName === 'roNo').disabled = false;
      this.form.find(item => item.fieldName === 'customerName').disabled = false;
      this.form.find(item => item.fieldName === 'consultant').disabled = false;
      this.form.find(item => item.fieldName === 'partPlatformOrderNo').disabled = false;
      this.form.find(item => item.fieldName === 'type').disabled = false;
      this.form.find(item => item.fieldName === 'remark').disabled = false;
      this.cancelBtn = false;
      this.saveltBtn = false;
      this.addbtn = false;
      this.impbtn = false;
      this.buildBtn = true;
    },

    // 配件新增
    addFun() {
      if (this.form.find(item => item.fieldName === 'customerName').initialValue == null || this.form.find(item => item.fieldName === 'customerName').initialValue == '') {
        return this.$notify.warning({ title: '提示信息', message: '请先填写' + this.form.find(item => item.fieldName === 'customerName').label });
      }
      this.dialogTitle = `配件新增`;
      this.salesOrderAddVisible = true;
    },
    // 配件销售编辑按钮
    editHandle(row) {
      this.dialogTitle = `配件销售编辑`;
      this.formData = row;
      this.salesOrderChangeVisible = true;
    },
    // 删除选中行
    async deleteHandle(row) {
      let deleData = []; // 已保存可删除配件
      let deleRows = []; // 未保存配件
      // for (const row of this.selectRow) {
      //   if (row.PART_QUANTITY < 0) {
      //     return this.$notify.error({ title: '提示信息', message: '退料配件无法删除!' });
      //   }
      //   if (row.ITEM_ID) {
      //     deleData.push(row.ITEM_ID);
      //   } else {
      //     deleRows.push(row);
      //   }
      // }
      if (row.ITEM_ID) {
        deleData.push(row.ITEM_ID);
      } else {
        deleRows.push(row);
      }
      // if (this.selectRow[0].PART_QUANTITY < 0) {
      //   return this.$notify.error({ title: '提示信息', message: '退料配件无法删除!' });
      // }
      // if (this.delFlag) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // let row = this.selectRow[0];
          // this.items.push(row.ITEM_ID);
          // this.baseTable.EXECUTE_DELETE([row]);
          if (deleData.length > 0) {
            let res = await delSalesPartInfo(deleData.join(','));
            if (res.resultCode == 200) {
              this.$notify.success({ title: '提示信息', message: '删除成功' });
              this.listTable = [];
              let res1 = await partSalesItem(this.form.find(item => item.fieldName === 'salesPartNo').initialValue);
              this.listTable = res1.data;
            }
          } else {
            this.baseTable.EXECUTE_DELETE(deleRows);
          }
        })
        .catch(() => {});
      // } else {
      //   this.$notify.error({ title: '提示信息', message: '该配件已出库，无法删除配件!' });
      // }
    },
    // 配件销售编辑页面保存
    changeEdit(obj) {
      // this.syncTableList[obj.$index] = Object.assign({}, obj);
      // 编辑数据赋值
      this.syncTableList.forEach(x => {
        if (x.STORAGE_CODE == obj.STORAGE_CODE && x.STORAGE_POSITION_CODE == obj.STORAGE_POSITION_CODE && x.PART_NO == obj.PART_NO) {
          x.SALES_TYPE = obj.SALES_TYPE;
          x.UNIT_CODE = obj.UNIT_CODE;
          x.PART_QUANTITY = obj.PART_QUANTITY;
          x.PART_SALES_PRICE = obj.PART_SALES_PRICE;
          x.PART_SALES_PRICE_NOTAX = obj.PART_SALES_PRICE_NOTAX;
          x.SALES_AMOUNT = obj.SALES_AMOUNT;
          x.PART_SALES_AMOUNT_NOTAX = obj.PART_SALES_AMOUNT_NOTAX;
          x.DISCOUNT = obj.DISCOUNT;
          x.PART_SALES_AMOUNT = obj.PART_SALES_AMOUNT;
          x.CREATED_BY = obj.CREATED_BY;
          x.IS_NEGATIVE = obj.IS_NEGATIVE;
          x.BATTERY_SEQUENCE = obj.BATTERY_SEQUENCE;
          x.PRICE_TYPE = obj.PRICE_TYPE;
          x.PRICE_RATE = obj.PRICE_RATE;
          x.COST_PRICE = obj.COST_PRICE;
          x.NODE_PRICE = obj.NODE_PRICE;
          x.IS_FINISHED = obj.IS_FINISHED;
          x.itemIdAdd = obj.itemIdAdd;
          x.flag = obj.flag;
          x.PART_COST_AMOUNT = obj.PART_COST_AMOUNT;
          x.ITEM_ID = obj.ITEM_ID;
          x.isShort = obj.isShort;
          x.USEABLE_STOCK = obj.USEABLE_STOCK;
          x.LATEST_PRICE = obj.LATEST_PRICE;
          return;
        }
      });

      // 从新调用同步方法
      this.syncTableFun(this.syncTableList);
      this.saveltBtn = false;
      this.outStockBtn = true;
      this.salesOrderChangeVisible = false;
    },
    // 取消
    async cancel() {
      const salesNo = this.form.find(item => item.fieldName === 'salesPartNo').initialValue;
      let res = [];
      if (salesNo != null) {
        // res = await unLocked(salesNo);
        // if (res.resultCode == 200) {
        // } else {
        //   // this.$notify.error({ title: '提示信息', message: res.errMsg || '解锁失败!' });
        // }
      }
      this.$refs.form.RESET_FORM();
      this.listTable = [];
      this.deleteList = [];

      this.form.find(item => item.fieldName === 'salesPartNo').disabled = false;
      this.form.find(item => item.fieldName === 'roNo').disabled = true;
      this.form.find(item => item.fieldName === 'customerName').disabled = true;
      this.form.find(item => item.fieldName === 'partPlatformOrderNo').disabled = true;
      this.form.find(item => item.fieldName === 'consultant').disabled = true;
      this.form.find(item => item.fieldName === 'customerName').label = '客户名称';
      this.form.find(item => item.fieldName === 'customerName').rules[0].message = '请选择客户';
      this.form.find(item => item.fieldName === 'type').disabled = true;
      this.form.find(item => item.fieldName === 'remark').disabled = true;
      this.buildBtn = false;
      this.saveltBtn = true;
      this.outStockBtn = true;
      this.cancelBtn = true;
      this.printlSalesBtn = true;
      this.printlSettlementBtn = true;
      this.printFlag = true; // 打印按钮
      this.deleteBtnState = true;
      this.addbtn = true;
      this.impbtn = true;
      this.exportmolbtn = false;
      this.exportbtn = true;
      this.columns.find(x => x.dataIndex == 'BATTERY_SEQUENCE').disabled = false;
      this.customerCode = '';
    },

    // 保存后可以进行出库操作
    async saveSales() {
      const orderNo = this.form.find(item => item.fieldName === 'roNo').initialValue;
      const salesPartNo = this.form.find(item => item.fieldName === 'salesPartNo').initialValue;
      let res = [];
      let ty = false;
      if (this.syncTableList.length == 0) {
        return this.$notify.warning({ title: '提示信息', message: '配件不能为空，请添加配件！' });
      }
      let customer = this.form.find(item => item.fieldName === 'customerName').initialValue;
      if (!customer) {
        return this.$notify.warning({ title: '提示信息', message: '请输入客户代码！' });
      }
      let nullList = '';
      for (let i = 0; i < this.syncTableList.length; i++) {
        if (this.syncTableList[i].PART_SALES_PRICE == 0.0) {
          nullList += this.syncTableList[i].PART_NAME + '配件销售单价为0,';
        }
        if (this.syncTableList[i].PART_QUANTITY == 0.0) {
          nullList += this.syncTableList[i].PART_NAME + '配件数量为0,';
        }
        if (this.syncTableList[i].DISCOUNT == 0.0) {
          nullList += this.syncTableList[i].PART_NAME + '折扣率0,';
        }
      }
      if (this.baseTable.GET_REQUIRED_ERROR() == null) {
        this.$confirm(nullList + '是否确认保存?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            // 校验客户信息是否存在

            // 工单号不为空的时候校验工单是否存在
            if (orderNo != null) {
              res = await roNo({ roNo: orderNo, salesPartNo: salesPartNo });
              if (res.data == 10041001) {
                return this.$notify.error({ title: '提示信息', message: '该工单号已经有对应的销售单！' });
              }
            }
            // 获取同步数据循环校验
            for (let i = 0; i < this.syncTableList.length; i++) {
              if (this.syncTableList[i].IS_FINISHED != 10041001) {
                let rea = await partSalesIfBear(this.syncTableList[i].STORAGE_CODE, this.syncTableList[i].PART_NO);
                if (rea.resultCode == 200) {
                  if (rea.data != null) {
                    // 有缺料的情况对明细状态赋值
                    this.syncTableList[i].isShort = 10041001;
                    this.checkData.push(rea.data);
                  }
                } else {
                  // return this.$notify.error({ title: '提示信息', message: res.errMsg });
                }
              }
            }
            // 存在缺料数量时候跳转到库存页面
            // if (this.checkData.length > 0) {
            //   this.flagStuats = false;
            //   this.checkStockVisible = true;
            // }

            if (this.flagStuats == true) {
              var list = [];
              console.log(this.syncTableList);
              console.log(this.listTable);
              this.syncTableList.forEach(x => {
                // 转换字段驼峰发送请求到DTO
                let itemList = {
                  salesType: x.SALES_TYPE,
                  latestPrice: x.LATEST_PRICE,
                  storageCode: x.STORAGE_CODE,
                  storagePositionCode: x.STORAGE_POSITION_CODE,
                  partNo: x.PART_NO,
                  partName: x.PART_NAME,
                  unitCode: x.UNIT_CODE,
                  partQuantity: x.PART_QUANTITY,
                  partSalesPrice: this.numFilter(x.PART_SALES_PRICE),
                  salesAmount: this.numFilter(x.SALES_AMOUNT),
                  partSalesAmount: this.numFilter(x.SALES_AMOUNT * x.DISCOUNT),
                  discount: x.DISCOUNT,
                  oldSalesPartNo: x.OLD_SALES_PART_NO,
                  priceType: x.PRICE_TYPE,
                  priceRate: x.PRICE_RATE,
                  partCostPrice: this.numFilter(x.COST_PRICE ? x.COST_PRICE : 0),
                  isFinished: x.IS_FINISHED,
                  partSalesPriceNotax: x.PART_SALES_PRICE_NOTAX,
                  partSalesAmountNotax: this.numFilter(x.PART_SALES_PRICE_NOTAX * x.PART_QUANTITY),
                  partCostAmount: this.numFilter((x.COST_PRICE ? x.COST_PRICE : 0) * x.PART_QUANTITY),
                  isShort: this.isShort,
                  itemIdStatus: x.itemIdStatus,
                  flag: x.flag,
                  itemId: x.ITEM_ID,
                  batterySequence: x.BATTERY_SEQUENCE || '',
                  partPlatformOrderNo: x.PART_PLATFORM_ORDER_NO || ''
                };
                list.push(itemList);
              });
              console.log(list);
              this.syncTableList.forEach(x => {
                if (x.IS_FINISHED === 10041001) {
                  ty = true;
                  return;
                }
              });
              this.$refs.form.SUBMIT_FORM();
              this.$refs.form2.SUBMIT_FORM();

              let result = await save({
                ...this.fetchParam,
                ...this.fetchParam2,
                partSalestable: list,
                remark: this.form.find(item => item.fieldName === 'remark').initialValue,
                customerCode: this.customerCode,
                vin: this.VIN,
                items: this.items.join(),
                ptype: this.ptype ? this.ptype : null // 模块区分
                // department: this.form.find(item => item.fieldName === 'department').initialValue, // 部门
                // profitCenter: this.form.find(item => item.fieldName === 'profitCenter').initialValue ? this.form.find(item => item.fieldName === 'profitCenter').initialValue : null // 利润中心
              });
              if (result.resultCode == 200) {
                this.form.find(item => item.fieldName === 'salesPartNo').initialValue = result.data;
                this.listTable = [];

                let res = await partSalesItem(result.data);
                this.baseTable.EXECUTE_INSERT(res.data);

                this.form.find(item => item.fieldName === 'type').disabled = true;
                this.outStockBtn = false;
                // this.saveltBtn = true;
                this.deleteBtnState = ty;
                this.items = [];
                this.$notify.success({ title: '提示信息', message: '保存成功' });

                // 开放打印按钮
                // this.printlSalesBtn = false;
                // this.printlSettlementBtn = false;
                this.deleteBtnState = false;
              }
            }
          })
          .catch(() => {});
      }
    },

    // 出库
    async outStock() {
      let types = true;
      for (let i = 0; i < this.syncTableList.length; i++) {
        if (this.syncTableList[i].SALES_TYPE === 80961002 && !this.customerCodeIn) {
          types = false;
          return this.$notify.warning({ title: '提示信息', message: '配件含有一进一出配件，供应商不能为空' });
        }

        if (this.syncTableList[i].SALES_TYPE === 80961002) {
          types = false;
          return this.$notify.warning({ title: '提示信息', message: '配件含有一进一出配件，税率不能为空' });
        }
        if (this.syncTableList[i].PART_SALES_PRICE == 0) {
          let status = await this.$confirm(this.syncTableList[i].PART_NAME + '销售材料费为0是否确认出库?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          });
          if (status !== 'confirm') {
            return;
          }
        }
        if (this.syncTableList[i].SALES_TYPE === 80961001) {
          await getStorageNum(this.syncTableList[i].STORAGE_CODE, this.syncTableList[i].PART_NO, this.form.find(item => item.fieldName === 'salesPartNo').initialValue).then(res => {
            console.log(res.data);
            if (res.data === '1') {
              types = false;
              return this.$notify.warning({ title: '提示信息', message: this.syncTableList[i].PART_NO + '配件缺料，不能出库！' });
            }
          });
        }
      }
      // console.log(12321);

      if (types) {
        var list = [];
        this.syncTableList.forEach(x => {
          let itemList = {
            latestPrice: x.LATEST_PRICE,
            salesType: x.SALES_TYPE,
            storageCode: x.STORAGE_CODE,
            storagePositionCode: x.STORAGE_POSITION_CODE,
            partNo: x.PART_NO,
            partName: x.PART_NAME,
            unitCode: x.UNIT_CODE,
            partQuantity: x.PART_QUANTITY,
            partSalesPrice: this.numFilter(x.PART_SALES_PRICE),
            salesAmount: this.numFilter(x.SALES_AMOUNT),
            partSalesAmount: x.PART_SALES_AMOUNT,
            discount: x.DISCOUNT,
            oldSalesPartNo: x.OLD_SALES_PART_NO,
            priceType: x.PRICE_TYPE,
            priceRate: x.PRICE_RATE,
            partCostPrice: this.numFilter(x.COST_PRICE ? x.COST_PRICE : 0),
            isFinished: x.IS_FINISHED,
            partSalesPriceNotax: this.numFilter(x.PART_SALES_PRICE) / (+this.rate + 1),
            partSalesAmountNotax: (this.numFilter(x.PART_SALES_PRICE) / (+this.rate + 1)) * this.numFilter(x.PART_QUANTITY),
            partCostAmount: this.numFilter((x.COST_PRICE ? x.COST_PRICE : 0) * x.PART_QUANTITY), //
            isShort: this.isShort,
            flag: x.flag,
            itemId: x.ITEM_ID,
            inAmount: this.formList.find(item => item.fieldName === 'edtMoney').initialValue
          };
          list.push(itemList);
        });
        this.$refs.form.SUBMIT_FORM();
        this.$refs.form2.SUBMIT_FORM();
        // this.outStockBtn = true;
        console.log(this.syncTableList, 'this.syncTableList');
        let flag = false;
        let enterRecordFlag = false;
        this.syncTableList.forEach(x => {
          if (x.PART_SALES_PRICE < x.COST_PRICE) {
            flag = true;
            return;
          }
        });
        let obj = {
          ...this.fetchParam,
          ...this.fetchParam2,
          partSalestable: list,
          remark: this.form.find(item => item.fieldName === 'remark').initialValue,
          customerCode: this.customerCode,
          customerCodeIn: this.customerCodeIn,
          vin: this.VIN
        };
        let res = {};
        if (flag) {
          if (isAuthorized('1313', '13131008')) {
            res = await enterRecord(obj);
          } else {
            this.$notify({
              title: '警告',
              message: '销售单价小于含税成本价，您无出库权限！',
              type: 'warning'
            });
          }
        } else {
          res = await enterRecord(obj);
        }

        if (res.resultCode == 200) {
          this.outStockBtn = true; // 关闭出库
          this.addbtn = true; // 关闭新增
          this.saveltBtn = true; // 关闭保存
          this.impbtn = true; // 关闭导入
          this.deleteBtnState = true; // 关闭作废
          this.exportbtn = false; // 打开导出
          this.printlSalesBtn = false; // 打开打印
          this.printFlag = false; // 打开打印入库单
          this.printlSettlementBtn = false;
          this.form.find(item => item.fieldName === 'roNo').disabled = true; // 禁用工单
          this.form.find(item => item.fieldName === 'consultant').disabled = true;
          this.form.find(item => item.fieldName === 'remark').disabled = true; // 禁用备注
          this.form.find(item => item.fieldName === 'customerName').disabled = true; // 禁用客户
          this.form.find(item => item.fieldName === 'type').disabled = true; // 禁用客户
          let resd = await partSalesItem(this.form.find(item => item.fieldName === 'salesPartNo').initialValue);
          this.baseTable.EXECUTE_DELETE(this.syncTableList);
          this.baseTable.EXECUTE_INSERT(resd.data);
          this.printData();
          this.printDataTwo();
          this.$nextTick(() => {
            this.columns.find(x => x.dataIndex == 'BATTERY_SEQUENCE').disabled = true;
          });
          return this.$notify.success({ title: '提示信息', message: '出库成功!' });
        } else {
          this.outStockBtn = false;
          // return this.$notify.error({ title: '提示信息', message: res.errMsg || '出库失败!' });
        }
      }
    },
    deleteAllSales() {
      this.$confirm('是否删除过期单据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        deleteAll(1).then(res => {
          if (res.resultCode == 200) {
            this.$notify.success({ title: '提示信息', message: '删除成功!' });
          }
        });
      });
    },
    // 作废
    deleteSales() {
      const salesNo = this.form.find(item => item.fieldName === 'salesPartNo').initialValue;
      this.$confirm('是否作废?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await deleted(salesNo);
          if (res.resultCode == 200) {
            // 作废成功后重置刷新页面
            this.$refs.form.RESET_FORM();
            // 该方法因开发时候组件冲突问题才用此方法,后续有更好方法可以优化
            // 清空table中所有行元素
            for (let i = 0; i < this.syncTableList.length; i++) {
              this.deleteList.push(this.syncTableList[i]);
            }
            this.baseTable.EXECUTE_DELETE(this.deleteList);
            this.deleteList = [];

            this.form.find(item => item.fieldName === 'salesPartNo').disabled = false;
            this.form.find(item => item.fieldName === 'type').disabled = false;
            this.form.find(item => item.fieldName === 'roNo').disabled = true;
            this.form.find(item => item.fieldName === 'customerName').disabled = true;
            this.form.find(item => item.fieldName === 'consultant').disabled = true;
            this.form.find(item => item.fieldName === 'customerName').label = '客户名称';
            this.form.find(item => item.fieldName === 'customerName').rules[0].message = '请选择客户';
            this.buildBtn = false;
            this.saveltBtn = true;
            this.outStockBtn = true;
            this.cancelBtn = true;
            this.printlSalesBtn = true;
            this.printFlag = true;
            this.printlSettlementBtn = true;
            this.deleteBtnState = true;
            this.addbtn = true;
            this.exportmolbtn = false;
            this.impbtn = true;
            this.exportbtn = true;

            return this.$notify.success({ title: '提示信息', message: '作废成功!' });
          } else {
            // this.$notify.error({ title: '提示信息', message: res.errMsg || '作废失败!' });
          }
        })
        .catch(() => {});
    },

    exportModel() {
      this.exportModelLoading = true;
      exportSalesModel().then(res => {
        exportExcelFile(res.data, '配件销售模板');
        this.exportModelLoading = false;
      });
    },
    importFun() {},
    exportFun() {
      this.exportLoading = true;
      let personParam = localStorage.getItem('1313');
      // console.log(personParam.indexOf("13131005"))
      partSalesExport(this.form.find(x => x.fieldName === 'salesPartNo').initialValue, personParam).then(res => {
        exportExcelFile(res, '配件销售');
        this.exportLoading = false;
      });
    },
    // 工单号查询
    partsOrder() {
      this.salesNo = this.form.find(x => x.fieldName === 'salesPartNo').initialValue;
      this.visibleSales = true;
    },
    // 工单号查询
    networkOrderSearch() {
      this.networkOrder = { title: '会员订单', visible: true };
    },
    // 销售单号新增
    passValue(obj) {
      // 先对数据进行校验
      if (obj.PART_NO != '' && obj.STORAGE_CODE != '') {
        if (this.syncTableList.length > 0) {
          for (const item of this.syncTableList) {
            if (item.PART_NO == obj.PART_NO && item.STORAGE_CODE == obj.STORAGE_CODE) {
              return this.$notify.error({ title: '提示信息', message: '信息已存在，不允许重复添加!' });
            }
          }
        }
      }
      // 给折扣率和配件收费金额进行赋值
      this.$set(obj, 'IS_FINISHED', 10041002);
      this.$set(obj, 'DISCOUNT', 1);
      this.$refs.table.EXECUTE_INSERT(obj);
      // this.listTable = [...this.listTable];
      this.$notify.success({ title: '提示信息', message: '添加成功！' });
      this.form.find(item => item.fieldName === 'salesPartNo').disabled = true;
      this.form.find(item => item.fieldName === 'roNo').disabled = true;
      // this.form.find(item => item.fieldName === 'customerName').disabled = true;
      // this.form.find(item => item.fieldName === 'type').disabled = true;
      // this.form.find(item => item.fieldName === 'consultant').disabled = true;
      this.buildBtn = true;
      this.saveltBtn = false;
      this.cancelBtn = false;
    },
    // 销售单号查询确认
    async getSelectSales(obj, data) {
      this.visibleSales = false;
      this.finishStatus = obj.isFinish;
      if (data) {
        // 有退料信息
        this.form.find(item => item.fieldName === 'partPlatformOrderNo').disabled = true;
        this.form.find(item => item.fieldName === 'remark').initialValue = obj.REMARK;
        this.form.find(item => item.fieldName === 'customerName').initialValue = obj.CUSTOMER_NAME;
        this.form.find(item => item.fieldName === 'customerCode').initialValue = obj.CUSTOMER_CODE;
        this.customerCode = obj.CUSTOMER_CODE;
        this.form.find(item => item.fieldName === 'consultant').initialValue = obj.CONSULTANT;
        if (obj.CUSTOMER_TYPE == 'vehicleOwner') {
          this.form.find(item => item.fieldName === 'customerName').label = '车主';
          this.form.find(item => item.fieldName === 'type').initialValue = 'vehicleOwner';
          this.form.find(item => item.fieldName === 'customerName').rules[0].message = '请选择车主';
        } else {
          this.form.find(item => item.fieldName === 'customerName').label = '客户名称';
          this.form.find(item => item.fieldName === 'type').initialValue = 'customer';
          this.form.find(item => item.fieldName === 'customerName').rules[0].message = '请选择客户';
        }
        this.form.find(item => item.fieldName === 'roNo').disabled == true;
        this.form.find(item => item.fieldName === 'salesPartNo').disabled = true;
        this.form.find(item => item.fieldName === 'type').disabled = true;
        this.form.find(item => item.fieldName === 'customerName').disabled = true;
        this.form.find(item => item.fieldName === 'consultant').disabled = true;
        this.buildBtn = true;
        this.addbtn = true;
        this.impbtn = true;
        this.saveltBtn = false;
        this.cancelBtn = false;
        this.outStockBtn = true;
        this.deleteBtnState = true;
        this.baseTable.EXECUTE_INSERT(data);
        this.columns.find(x => x.dataIndex == 'BATTERY_SEQUENCE').disabled = true;
      } else {
        if (obj != null) {
          this.form.find(item => item.fieldName === 'partPlatformOrderNo').disabled = true;
          this.form.find(item => item.fieldName === 'remark').initialValue = obj.REMARK;
          this.form.find(item => item.fieldName === 'salesPartNo').initialValue = obj.SALES_PART_NO;
          this.form.find(item => item.fieldName === 'customerName').initialValue = obj.CUSTOMER_NAME;
          if (obj.CUSTOMER_TYPE == 'vehicleOwner') {
            this.form.find(item => item.fieldName === 'customerName').label = '车主';
            this.form.find(item => item.fieldName === 'type').initialValue = 'vehicleOwner';
            this.form.find(item => item.fieldName === 'customerName').rules[0].message = '请选择车主';
          } else {
            this.form.find(item => item.fieldName === 'customerName').label = '客户名称';
            this.form.find(item => item.fieldName === 'type').initialValue = 'customer';
            this.form.find(item => item.fieldName === 'customerName').rules[0].message = '请选择客户';
          }
          console.log(obj.isFinish, 'obj.isFinish');
          // 未出库的销售单
          let res = await partSalesItem(obj.SALES_PART_NO);
          if (res.resultCode == 200 && res.data[0].IS_FINISHED != 10041001) {
            if (obj.RO_NO != null) {
              this.form.find(item => item.fieldName === 'roNo').initialValue = obj.RO_NO;
              this.form.find(item => item.fieldName === 'roNo').disabled == true;
            } else {
              this.form.find(item => item.fieldName === 'roNo').disabled == false;
            }
            if (obj.CONSULTANT != null) {
              this.form.find(item => item.fieldName === 'consultant').initialValue = +obj.CONSULTANT;
            }
            this.baseTable.EXECUTE_INSERT(res.data);
            this.form.find(item => item.fieldName === 'salesPartNo').disabled = true;
            if (res.data[0].OLD_SALES_PART_NO) {
              this.form.find(item => item.fieldName === 'type').disabled = true;
              this.columns.find(x => x.dataIndex == 'BATTERY_SEQUENCE').disabled = true;
              this.form.find(item => item.fieldName === 'customerName').disabled = true;
              this.form.find(item => item.fieldName === 'consultant').disabled = true;
            } else {
              this.form.find(item => item.fieldName === 'type').disabled = false;
              this.form.find(item => item.fieldName === 'customerName').disabled = false;
              this.form.find(item => item.fieldName === 'consultant').disabled = false;
            }
            if (obj.BALANCE_STATUS != 10041001) {
              this.buildBtn = true;
              this.addbtn = false;
              this.impbtn = false;
              this.saveltBtn = false;
              this.cancelBtn = false;
              this.outStockBtn = false;
              this.deleteBtnState = false;
            } else {
              this.buildBtn = true;
              this.addbtn = true;
              this.impbtn = true;
              this.saveltBtn = true;
              this.cancelBtn = false;
              this.outStockBtn = false;
              this.deleteBtnState = true;
              // 已经结算的单子 设置PRICE_TYPE 不可用
              this.form.find(item => item.fieldName === 'PRICE_TYPE').disabled = true;
            }
            this.form.find(item => item.fieldName === 'remark').disabled = false;
          } else {
            // 出库的销售单
            this.enDisabled = true;
            if (obj.RO_NO != null) {
              this.form.find(item => item.fieldName === 'roNo').initialValue = obj.RO_NO;
            }
            if (obj.CONSULTANT != null) {
              this.form.find(item => item.fieldName === 'consultant').initialValue = +obj.CONSULTANT;
            }
            this.baseTable.EXECUTE_INSERT(res.data);

            this.form.find(item => item.fieldName === 'salesPartNo').disabled = true;
            this.form.find(item => item.fieldName === 'type').disabled = true;
            this.form.find(item => item.fieldName === 'customerName').disabled = true;
            this.form.find(item => item.fieldName === 'consultant').disabled = true;
            this.buildBtn = true;
            this.addbtn = true;
            this.saveltBtn = true;
            this.cancelBtn = false;
            this.outStockBtn = true;
            this.deleteBtnState = true;
            this.form.find(item => item.fieldName === 'salesPartNo').disabled = true;
            this.form.find(item => item.fieldName === 'type').disabled = true;
            this.form.find(item => item.fieldName === 'customerName').disabled = true;
            this.buildBtn = true;

            this.cancelBtn = false;
            this.printlSalesBtn = false;
            this.printFlag = false;
            this.printlSettlementBtn = false;
            this.columns.find(x => x.dataIndex == 'BATTERY_SEQUENCE').disabled = true;
          }
          this.exportbtn = false;
        }
      }
    },

    // 打开工单查询
    order() {
      this.orderVisible = true;
    },
    // 工单查询 确认
    getSelectNo(obj) {
      this.orderVisible = false;
      if (obj != null) {
        // 如果返回的值不为空
        // 工单号查询返回到父组件的值
        this.form.find(item => item.fieldName === 'roNo').initialValue = obj[0].RO_NO;
        // 带出相关车主信息
        this.form.find(item => item.fieldName === 'type').initialValue = 'vehicleOwner';
        this.form.find(item => item.fieldName === 'customerName').label = '车主';
        this.form.find(item => item.fieldName === 'customerName').initialValue = obj[0].OWNER_NAME;
        this.form.find(item => item.fieldName === 'customerName').rules[0].message = '请选择车主';
        this.customerCode = obj[0].OWNER_NO;
        this.VIN = obj[0].VIN;
        this.form.find(item => item.fieldName === 'roNo').disabled = true;
        this.form.find(item => item.fieldName === 'type').disabled = true;
        this.form.find(item => item.fieldName === 'customerName').disabled = true;
      }
    },
    // 缺料页面传值
    async check1(val) {
      this.checkData = [];
      this.flagStuats = true;
      this.checkStockVisible = false;
      let ty = false;
      var list = [];
      this.syncTableList.forEach(x => {
        // 转换字段驼峰发送请求到DTO
        let itemList = {
          salesType: x.SALES_TYPE,
          latestPrice: x.LATEST_PRICE,
          storageCode: x.STORAGE_CODE,
          storagePositionCode: x.STORAGE_POSITION_CODE,
          partNo: x.PART_NO,
          partName: x.PART_NAME,
          unitCode: x.UNIT_CODE,
          partQuantity: x.PART_QUANTITY,
          partSalesPrice: this.numFilter(x.PART_SALES_PRICE),
          salesAmount: this.numFilter(x.SALES_AMOUNT),
          partSalesAmount: x.PART_SALES_AMOUNT,
          discount: x.DISCOUNT,
          oldSalesPartNo: x.OLD_SALES_PART_NO,
          priceType: x.PRICE_TYPE,
          priceRate: x.PRICE_RATE,
          partCostPrice: this.numFilter(x.COST_PRICE ? x.COST_PRICE : 0),
          isFinished: x.IS_FINISHED,
          partSalesPriceNotax: x.PART_SALES_PRICE_NOTAX,
          partSalesAmountNotax: this.numFilter(x.PART_SALES_PRICE_NOTAX * x.PART_QUANTITY),
          partCostAmount: this.numFilter((x.COST_PRICE ? x.COST_PRICE : 0) * x.PART_QUANTITY),
          isShort: this.isShort,
          itemIdStatus: x.itemIdStatus,
          flag: x.flag,
          itemId: x.ITEM_ID
        };
        list.push(itemList);
      });
      this.syncTableList.forEach(x => {
        if (x.IS_FINISHED === 10041001) {
          ty = true;
          return;
        }
      });
      this.$refs.form.SUBMIT_FORM();
      this.$refs.form2.SUBMIT_FORM();
      let result = await save({
        ...this.fetchParam,
        ...this.fetchParam2,
        partSalestable: list,
        remark: this.form.find(item => item.fieldName === 'remark').initialValue,
        customerCode: this.customerCode,
        vin: this.VIN,
        items: this.items.join()
      });
      if (result.resultCode == 200) {
        this.form.find(item => item.fieldName === 'salesPartNo').initialValue = result.data;
        this.listTable = [];

        let res = await partSalesItem(result.data);
        this.baseTable.EXECUTE_INSERT(res.data);

        this.form.find(item => item.fieldName === 'type').disabled = true;
        this.outStockBtn = false;
        this.saveltBtn = true;
        this.deleteBtnState = ty;
        this.items = [];
        return this.$notify.success({ title: '提示信息', message: '保存成功' });
      }
    },
    customer(val) {
      this.keys = val;
      this.customerVisible = true;
    },
    vehicle() {
      this.vehicleOwnerVisible = true;
    },
    async searchstore() {
      const res = await getStroageList();
      this.codeName = this.columns.find(x => x.dataIndex == 'STORAGE_CODE').dictItems = this.columns.find(x => x.dataIndex == 'STORAGE_CODE').filterItems = this.columns.find(
        x => x.dataIndex == 'STORAGE_CODE'
      ).editItems = res.data.map(x => ({
        value: x.STORAGE_CODE,
        text: x.STORAGE_NAME
      }));
    },
    getStorageName(storageCode) {
      const item = this.codeName.find(x => {
        return x.value == storageCode;
      });
      return item ? item.text : '';
    },
    // 获取车主信息
    getvehicleOwner(val) {
      this.form.find(item => item.fieldName === 'customerName').initialValue = val[0].OWNER_NAME;
      this.customerCode = val[0].OWNER_NO;
      this.VIN = val[0].VIN;
      this.vehicleOwnerVisible = false;
    },
    // 循环结算传入的列表数组的含税不含税单价（新增配件初始化数据用）
    formatPartsData(list) {
      list.map((item, index) => {
        // 处理采购数量，套餐类型单独处理 incount数量x订购套数
        this.$set(list[index], 'PART_SALES_PRICE_NOTAX', item.PART_SALES_PRICE);
        this.$set(list[index], 'SALES_AMOUNT', item.PART_SALES_PRICE * item.PART_QUANTITY);
        this.$set(list[index], 'PART_SALES_AMOUNT_NOTAX', item.PART_SALES_PRICE_NOTAX * item.PART_QUANTITY);
        this.$set(list[index], 'PART_SALES_AMOUNT', item.SALES_AMOUNT * item.DISCOUNT);
      });
    },
    // 往配件table列表中插入数据
    handleDetailSelectConfirm(e, data) {
      let partList = e;

      // 校验重复配件
      let newPartArr = [];
      let repeatingPartArr = []; // 重复配件，新配件
      console.log(partList, 'partList:::');
      console.log(this.syncTableList, 'listTable:::');
      partList.map(item => {
        if (this.syncTableList.find(x => x.PART_NO == item.PART_NO)) {
          repeatingPartArr.push(item);
        } else {
          newPartArr.push(item);
        }
      });
      if (repeatingPartArr.length) {
        let idsArr = repeatingPartArr.map(item => item.partNo);
        notifyAction('此订单类型禁止添加重复配件，配件代码：' + idsArr.join(','), 'warning');
      }

      newPartArr = JSON.parse(JSON.stringify(newPartArr)); // 浅拷贝防止原始数据修改
      this.formatPartsData(newPartArr);
      this.baseTable.EXECUTE_INSERT(newPartArr);
      if (data.length > 0) {
        let errorData = data.map(x => {
          if (x.result === '查询不到库存') {
            return '仓库：' + x.storageCode + '中配件：' + x.partNo + '不存在';
          } else {
            return x.partNo + '配件销售数量为负';
          }
        });
        this.$notify.warning({ title: '提示信息', message: `导入成功，${errorData.join('，')}，请确认模板` });
      } else {
        notifyAction('配件导入成功', 'success');
      }
      // this.partDetailIdList = partList.map(item => item.partNo);
    },
    // 获取客户页面信息
    getCustomer(val) {
      console.log(val, 'customer:::');
      if (this.keys === 'customerName') {
        this.form.find(item => item.fieldName === 'customerName').initialValue = val[0].CUSTOMER_NAME;
        this.form.find(item => item.fieldName === 'customerName').rules[0].message = '请选择客户';
        this.customerCode = val[0].CUSTOMER_CODE;
      } else {
        this.form.find(item => item.fieldName === 'customerNameIn').initialValue = val[0].CUSTOMER_NAME;
        this.form.find(item => item.fieldName === 'customerName').rules[0].message = '请选择客户';
        this.customerCodeIn = val[0].CUSTOMER_CODE;
      }
      // this.salesBasePriceType = val[0].SALES_BASE_PRICE_TYPE;
      // this.priceAddRate = val[0].PRICE_RATE;
      this.customerVisible = false;
    },
    // 表格同步数据
    syncTableFun(val) {
      let SalesAmountTotal = 0;
      let ChargeAmountTotal = 0;
      let partNum = 0;
      let temp = [];
      val.forEach(x => {
        SalesAmountTotal += Number(x.SALES_AMOUNT);
        ChargeAmountTotal += Number(x.SALES_AMOUNT) * Number(x.DISCOUNT);
        partNum += Number(x.PART_QUANTITY);
        temp.push(x.PART_NO);
        if (x.BALANCE_STATUS == 10041001 || x.PART_QUANTITY < 0) {
          this.baseTable.SET_CELL_DISABLED(x, 'DISCOUNT', true);
          this.baseTable.SET_CELL_DISABLED(x, 'PART_QUANTITY', true);
          this.baseTable.SET_CELL_DISABLED(x, 'PART_SALES_PRICE', true);
          this.baseTable.SET_CELL_DISABLED(x, 'PRICE_TYPE', true);
        } else {
          this.baseTable.SET_CELL_DISABLED(x, 'DISCOUNT', false);
        }
      });
      // this.formList.find(item => item.fieldName === 'kindNum').initialValue = [...new Set(temp)].length;
      // this.formList.find(item => item.fieldName === 'partNum').initialValue = this.numFilter(partNum);
      this.formList.find(item => item.fieldName === 'edtMoney').initialValue = this.numFilter(SalesAmountTotal);
      this.formList.find(item => item.fieldName === 'salesPartAmount').initialValue = this.numFilter(ChargeAmountTotal);
      this.syncTableList = val;
      // this.listTable = val;
    },
    // 打印销售单
    async printlSales() {
      const res = await printData(this.form.find(item => item.fieldName === 'salesPartNo').initialValue);
      let explainArr = [];
      // 获取公司信息
      // let componyInfo = '';
      // try {
      //   componyInfo = await queryCompanyInforById({
      //     owenrCode: getCompanyId()
      //   });
      // } catch (err) {
      //   console.log('获取公司信息失败', err);
      // }
      // 查询配件销售单说明
      // try {
      //   let explainRes = await doSearch({ module: 'spa' });
      //   let explainKeyArr = ['XSDSM', 'XSDSM1', 'XSDSM2'];
      //   // "XSDSM" "XSDSM1" "XSDSM2" bParaValue
      //   if (explainRes.resultCode == 200) {
      //     explainKeyArr.map(item => {
      //       let itemStr = explainRes.data.find(item2 => item2.para == item) ? explainRes.data.find(item2 => item2.para == item).bParaValue : '';
      //       itemStr && explainArr.push(itemStr);
      //     });
      //   }
      //   console.log(explainArr, '配件系统参数，说明部分。。。。。');
      // } catch (err) {
      //   console.log(err, '获取配件销售单说明失败');
      // }
      this.handleDyone = true;
      this.SalesprintList = {
        ...res.data
        // compInfo: componyInfo.data
      };
      console.log(this.SalesprintList);
      try {
        this.SalesprintList.baseInfo.USER_NAME = this.cunUserList.find(item => item.userId == this.SalesprintList.baseInfo.USER_ID).employeeName || '';
        this.SalesprintList.baseInfo.CREATED_NAME = this.cunUserList.find(item => item.userId == this.SalesprintList.baseInfo.CREATED_BY).employeeName || '';
      } catch (err) {
        console.log(err);
      }
      if (this.SalesprintList.baseInfo.SALES_PART_AMOUNT) {
        this.SalesprintList.baseInfo.SALES_PART_AMOUNT = setRound(this.SalesprintList.baseInfo.SALES_PART_AMOUNT);
        console.log(sessionStorage.getItem('precision'), sessionStorage.getItem('settlementType'), 'SALES_PART_AMOUNT', this.SalesprintList.baseInfo.SALES_PART_AMOUNT);
      }

      var str = this.form.find(x => x.fieldName == 'consultant').initialValue;
      if (typeof str === 'undefined') {
        this.SalesprintList.baseInfo.consultant = '';
      } else {
        var text = this.form.find(x => x.fieldName == 'consultant').itemList.find(item => item.value === str).text;
        this.SalesprintList.baseInfo.consultant = text;
      }
      this.$nextTick(() => {
        this.$refs.Salesprint.EXCUTE_PRINT();
      });
    },
    // 打印销售结算单
    async printlSettlement() {
      this.getToolParams();
      const res = await printDataTwo(this.form.find(item => item.fieldName === 'salesPartNo').initialValue);
      this.handleDdtwo = true;
      // 获取公司信息
      let componyInfo = '';
      try {
        componyInfo = await queryCompanyInforById({
          owenrCode: getCompanyId()
        });
      } catch (err) {
        console.log('获取公司信息失败', err);
      }
      this.SettlementprintList = {
        ...res.data,
        compInfo: componyInfo.data
      };
      if (this.SettlementprintList.baseInfo.SALES_PART_AMOUNT) {
        this.SettlementprintList.baseInfo.SALES_PART_AMOUNT = setRound(this.SettlementprintList.baseInfo.SALES_PART_AMOUNT);
      }
      // 打印会员信息获取会员信息
      let params = {
        orderType: 2,
        salesPartNo: this.form.find(item => item.fieldName === 'salesPartNo').initialValue || '',
        balanceNo: this.listTable[0].BALANCE_NO
      };

      try {
        let res = await queryVipInfoByBillNo(params);
        if (res.resultCode == 200 && res.data.result == true) {
          this.SettlementprintList.vipCardData = res.data.ReturnMemberInfo;
        }
      } catch (err) {
        console.log('获取会员信息失败');
      }
      this.cunUserList.forEach(x => {
        if (this.SettlementprintList.baseInfo.USER_ID == x.userId) {
          this.SettlementprintList.baseInfo.USER_NAME = x.employeeName;
        }
      });

      var str = this.form.find(x => x.fieldName == 'consultant').initialValue;
      if (typeof str === 'undefined') {
        this.SettlementprintList.baseInfo.consultant = '';
      } else {
        var text = this.form.find(x => x.fieldName == 'consultant').itemList.find(item => item.value === str).text;
        this.SettlementprintList.baseInfo.consultant = text;
      }
      console.log('结算单说明', this.XSJSDSM);
      this.SettlementprintList.compInfo.remark = this.XSJSDSM;
      this.$nextTick(() => {
        this.$refs.Settlementsprint.EXCUTE_PRINT();
      });
      this.paraArr = [];
      this.XSJSDSM = '';
    },
    // 订单导入成功事件
    handleUploadChange(e) {
      if (e != 1) {
        console.log(e, 'e::');
        console.log('导入文件上传成功', e[e.length - 1].url);
        this.fileInitalValue = e;
        let excelData = _.cloneDeep(e[e.length - 1].url.result);
        for (const item of this.listTable) {
          for (const items of excelData) {
            if (item.PART_NO == items.PART_NO && item.STORAGE_CODE == items.STORAGE_CODE) {
              item.PART_QUANTITY = Number(item.PART_QUANTITY) + Number(items.PART_QUANTITY);
            }
          }
          excelData = excelData.filter(items => {
            return items.PART_NO != item.PART_NO || item.STORAGE_CODE != items.STORAGE_CODE;
          });
        }
        console.log(excelData, 'excelData');
        if (excelData.length) {
          this.formatPartsData(excelData);
        }
        this.handleDetailSelectConfirm(excelData, e[e.length - 1].url.errorList);
      }
    },
    // 查询出库单打印配置
    async queryOutboundPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJCK'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.outboundPrintParams = res.data[0];
        this.outboundPrintParams.vDirectPrint = this.outboundPrintParams.vDirectPrint === 0 ? '0' : this.outboundPrintParams.vDirectPrin;
      }
      console.log(this.outboundPrintParams, '出库单打印配置');
    },
    // 查询配件销售结算单打印配置
    async querySettlementPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJSXJS'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.settlementPrintParams = res.data[0];
        this.settlementPrintParams.vDirectPrint = this.settlementPrintParams.vDirectPrint === 0 ? '0' : this.settlementPrintParams.vDirectPrin;
      }
      console.log(this.settlementPrintParams, '结算单打印配置');
    },
    // 查询销售单打印配置
    async querySaleOrderPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJSX'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.saleOrderPrintParams = res.data[0];
        this.saleOrderPrintParams.vDirectPrint = this.saleOrderPrintParams.vDirectPrint === 0 ? '0' : this.saleOrderPrintParams.vDirectPrin;
      }
      console.log(this.settlementPrintParams, '销售单打印配置');
    }
  }
};
</script>
